package demo1;

/**
 * @Author liangzai
 * @Description:
 */
public class Demo {
        public ListNode head;

    public boolean contains(int key) {
        ListNode cur = head;
        while (cur != null) {
            if(cur.val == key) {
                return true;
            }
            cur = cur.next;
        }
        return false;
    }



public ListNode partition(int x) {
        // write code here
        ListNode bs = null;
        ListNode be = null;
        ListNode as = null;
        ListNode ae = null;
        ListNode cur = head;
        while (cur != null) {
        if(cur.val < x) {
        //第一次插入
        if(bs == null) {
        bs = be = cur;
        }else {
        be.next = cur;
        be = be.next;
        }
        }else {
        if(as == null) {
        as = ae = cur;
        }else {
        ae.next = cur;
        ae = ae.next;
        }
        }
        cur = cur.next;
        }
        if(bs == null) {
        return as;
        }
        be.next = as;
        //不管第二部分是否最后一个节点为空 都手动置为空
        if(as != null) {
        ae.next = null;
        }
        return bs;
        }

//10:13 我来写
public boolean chkPalindrome() {
        // write code here
        if(head == null) return true;
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
        fast = fast.next.next;
        slow = slow.next;
        }
        //slow 指向的位置 就是中间节点
        //2.进行翻转
        ListNode cur = slow.next;
        while (cur != null) {
        ListNode curN = cur.next;
        cur.next = slow;
        slow = cur;
        cur = curN;
        }
        //3.判断回文
        while (head != slow) {
        if(head.val != slow.val) {
        return false;
        }
        if(head.next == slow) {
        return true;
        }
        head = head.next;
        slow = slow.next;
        }
        return true;
        }

public boolean hasCycle() {
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
        fast = fast.next.next;
        slow = slow.next;
        if(fast == slow) {
        return true;
        }
        }
        return false;
        }

public void createLoop() {
        ListNode cur = head;
        while (cur.next != null) {
        cur = cur.next;
        }
        cur.next = head.next.next;
        }

public ListNode detectCycle() {
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
        fast = fast.next.next;
        slow = slow.next;
        if(fast == slow) {
        break;
        }
        }
        if(fast == null || fast.next == null) {
        return null;//没有环
        }
        slow = head;
        while (slow != fast) {
        fast = fast.next;
        slow = slow.next;
        }
        return slow;
        }

}